import React, {memo, useState, useEffect} from 'react'
import {
	Button,
	Input,
	Row,
	Col,
	Space,
	Table,
	Tree,
	message,
	Popconfirm,
	Form,
	TreeSelect,
} from 'antd'
import {history, connect} from 'umi'
import {
	getRoleList,
	deleteRole,
	roleShareUser,
	roleUnbindUser,
} from '@/service/system/role'
import Permissions from '@/components/Permissions'
import {getUseList} from '@/service/system/user'
import {getMenuList} from '@/service/system/menu'
import {translateDataToTree} from '@/utils/common/index'
import {getCompany} from '@/service/system/company'
import {downloadDocumentUrl} from '@/service/common/download'
import styles from './index.less'

const {Search} = Input
const roleAddShareDom = memo((props: {dispatch: any; user: any}) => {
	const orgId = props?.user?.orgId
	const currentMerchantId = props?.user?.currentMerchantId

	const [form] = Form.useForm()
	const [roleLoading, setRoleLoading] = useState(false)
	const [userLoading, setUserLoading] = useState(false)
	const [selectId, setSelectedId] = useState([])
	const [selectIds, setSelectedIds] = useState<any>()

	const [roleSource, setRoleSource] = useState<any>()
	const [roleId, setRoleIdSource] = useState('')
	const [roleName, setRoleNameSource] = useState('')
	const [userName, setUserNameSource] = useState('')
	const [userNameStr, setUserNameStrSource] = useState('')

	const [userSource, setUserSource] = useState([])
	const [menuSource, setMenuSource] = useState([])

	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
	const [orginSelectedRowKeys, setOrginSelectedRowKeys] = useState<
		React.Key[]
	>([])
	const [checkStrictly, setCheckStrictly] = useState(false)
	const [rowClassName, setRowClassNameSource] = useState<string | number>()

	const [orgSource, setOrgSource] = useState<any>()
	// 获取角色列表
	const roleList = () => {
		setRoleLoading(true)
		if (currentMerchantId) {
			getRoleList({merchantId: currentMerchantId, roleName})
				.then((res: any) => {
					if (res?.success) {
						setRoleSource(res?.data)
						setRoleIdSource(() => res?.data[0]?.id)
						setRowClassNameSource(res?.data[0]?.id)
						const ids = res?.data[0]?.permissionList?.map(
							(x: any) => x?.id,
						)
						setSelectedIds(() => ids)
					}
					setRoleLoading(false)
				})
				.catch(() => {
					setRoleLoading(false)
				})
		}
	}
	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
				if (currentMerchantId) {
					form.setFieldsValue({merchantId: currentMerchantId})
				} else {
					props.dispatch({
						type: 'user/updateCurrentMerchantId',
						payload: {
							currentMerchantId: list[0]?.id,
						},
					})
				}
			}
		})
	}
	// 获取公司
	useEffect(() => {
		onOrgFun()
	}, [orgId])
	// 用户和角色
	const getUserByRoleFun = () => {
		if (currentMerchantId && roleId) {
			getUseList({merchantId: currentMerchantId, roleId})
				.then((res: any) => {
					if (res?.success) {
						const ids = res?.data?.map(
							(item: {id: number}) => item.id,
						)
						setSelectedRowKeys(() => ids)
						setOrginSelectedRowKeys(() => ids)
					}
				})
				.catch(() => {
					setUserLoading(false)
				})
		}
	}
	// 用户列表
	const getUserFun = () => {
		setUserLoading(true)
		getUseList({merchantId: currentMerchantId, userName})
			.then((res: any) => {
				if (res?.success) {
					setUserSource(res.data)
					setUserLoading(false)
					getUserByRoleFun()
				}
			})
			.catch(() => {
				setUserLoading(false)
			})
	}

	const getObjectById = (dataSource: any, temp: any[] = []) => {
		const forFn = (arr: any) => {
			for (let i = 0; i < arr?.length; i += 1) {
				if (!arr[i]?.children || arr[i]?.children?.length === 0) {
					temp.push(arr[i])
				} else {
					forFn(arr[i]?.children)
				}
			}
		}
		forFn(dataSource)
		return temp
	}
	useEffect(() => {
		if (roleSource) {
			const l = getObjectById(menuSource, [])
			const ml = l?.map((n: any) => n.id)
			const idls = selectIds?.filter((item: any) => ml?.includes(item))
			setSelectedId(() => idls)
		}
	}, [menuSource, roleSource, selectIds])

	// 菜单列表
	const getMenuFun = () => {
		getMenuList().then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setMenuSource(list as any)
			}
		})
	}

	// 新增角色
	const onAddFun = () => {
		history.push({
			pathname: '/system/roleAddShare/add',
		})
	}

	// 编辑角色
	const onEditFun = (id: string) => {
		history.push({
			pathname: '/system/roleAddShare/edit',
			query: {
				id,
				type: 'edit',
			},
		})
	}

	// 复制角色
	const onCopyFun = (id: string) => {
		history.push({
			pathname: '/system/roleAddShare/add',
			query: {
				id,
				type: 'copy',
			},
		})
	}

	// 删除角色
	const onDeleteFun = (rId: any) => {
		deleteRole(rId).then((res: any) => {
			if (res?.success) {
				message.success(res.msg)
				roleList()
			}
		})
	}

	// 查看角色
	const onViewFun = (id: string) => {
		history.push({
			pathname: '/system/roleAddShare/view',
			query: {
				id,
			},
		})
	}

	const roleColumns = [
		{
			title: '角色名',
			key: 'name',
			width: 200,
			ellipsis: true,
			dataIndex: 'name',
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			ellipsis: true,
			key: 'opt',
			dataIndex: 'opt',
			algin: 'center',
			width: 150,
			render: (
				text: any,
				record: {
					permissionList(id: string, permissionList: any): void
					id: string
				},
			) => (
				<>
					<Permissions permissionID="amc_system_permission_roleAddShare_copy">
						<Button
							className="text_btn"
							type="link"
							size="small"
							onClick={() => onCopyFun(record.id)}>
							复制
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_roleAddShare_edit">
						<Button
							className="text_btn"
							type="link"
							size="small"
							onClick={() => onEditFun(record.id)}>
							编辑
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_roleAddShare_view">
						<Button
							className="text_btn"
							type="link"
							size="small"
							onClick={() => onViewFun(record.id)}>
							查看
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_permission_roleAddShare_delete">
						<Popconfirm
							placement="topLeft"
							title="你确定要删除该角色？"
							onConfirm={() => onDeleteFun(record.id)}
							okText="确定"
							cancelText="取消">
							<Button
								className="text_btn"
								type="link"
								size="small">
								删除
							</Button>
						</Popconfirm>
					</Permissions>
				</>
			),
		},
	]
	useEffect(() => {
		roleList()
	}, [roleName, currentMerchantId])

	const onUnbindFun = (id: any) => {
		roleUnbindUser(roleId, {
			userIds: id,
			merchantId: currentMerchantId,
		}).then((res) => {
			if (res.success) {
				message.success(res.msg)
				getUserFun()
			}
		})
	}

	const uesrColumns = [
		{
			title: '用户名-手机号',
			key: 'name',
			dataIndex: 'name',
			ellipsis: true,
			algin: 'center',
			render: (text: string, record: any) => (
				<Space>
					<span>
						{text} - {record.phone}
					</span>
				</Space>
			),
		},
		{
			title: '绑定',
			key: 'option',
			dataIndex: 'option',
			algin: 'center',
			ellipsis: true,
			render: (text: string, record: any) => (
				<Permissions permissionID="amc_system_permission_roleAddShare_unbind">
					{orginSelectedRowKeys.includes(record.id) ? (
						<Button
							type="link"
							size="small"
							onClick={() => onUnbindFun([record.id])}>
							取消绑定
						</Button>
					) : null}
				</Permissions>
			),
		},
	]

	useEffect(() => {
		getMenuFun()
	}, [currentMerchantId])

	useEffect(() => {
		if (currentMerchantId) {
			getUserFun()
		}
	}, [userName, roleId, currentMerchantId])

	// 角色搜索
	const onRoleSearch = (value: string) => {
		setRoleNameSource(() => value)
	}
	// 用户搜索
	const onUserSearch = (value: string) => {
		setUserNameSource(() => value)
	}

	// 选中角色
	const onSelectRow = (row: any) => {
		const ids = row.permissionList?.map((item: any) => item.id)
		setUserNameSource(() => '')
		setUserNameStrSource(() => '')
		setSelectedIds(() => ids)
		setRoleIdSource(() => row.id)
		setRowClassNameSource(row?.id)
	}

	// 用户勾选保存
	const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
		setSelectedRowKeys(newSelectedRowKeys)
	}

	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	}

	// 用户保存事件
	const onSaveFun = () => {
		roleShareUser(roleId, {
			userIdList: selectedRowKeys,
			merchantId: currentMerchantId,
		}).then((res: any) => {
			if (res.success) {
				message.success(res.msg)
				getUserFun()
			}
		})
	}
	const onChange = (key: string | string[]) => {
		props.dispatch({
			type: 'user/updateCurrentMerchantId',
			payload: {
				currentMerchantId: key,
			},
		})
	}
	// 设置行名称
	const setRowClassName = (record: {id: any}) =>
		record.id === rowClassName ? `clickRowStyl` : ''

	// 表单提交
	return (
		<div className={styles.content}>
			<div className="searchForm">
				<Form
					name="basic"
					form={form}
					layout="horizontal"
					labelCol={{flex: '80px'}}
					initialValues={{remember: true}}
					autoComplete="off">
					<Row gutter={12}>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="组织机构"
								name="merchantId"
								rules={[{required: true}]}>
								<TreeSelect
									showSearch
									treeNodeFilterProp="name"
									style={{width: '100%'}}
									dropdownStyle={{
										maxHeight: 400,
										overflow: 'auto',
									}}
									placeholder="请输入组织机构"
									treeDefaultExpandAll
									onChange={onChange}
									fieldNames={{
										label: 'name',
										value: 'id',
									}}
									treeData={orgSource}
								/>
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</div>
			<Row gutter={12}>
				<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
					<Row>
						<Col sm={{span: 24}} className="title">
							角色
						</Col>
						<Col
							sm={{span: 24}}
							md={{span: 24}}
							lg={{span: 24}}
							className="search">
							<Space size={12}>
								<Search
									placeholder="请输入角色名"
									allowClear
									enterButton="搜索"
									onSearch={onRoleSearch}
								/>
								<Permissions permissionID="amc_system_permission_roleAddShare_addRole">
									<Button
										type="primary"
										onClick={() => onAddFun()}>
										添加角色
									</Button>
								</Permissions>
								<Button
									onClick={() => {
										if (!roleId) {
											message.error(
												'角色Id不存在,请选择一个角色',
											)
										} else {
											downloadDocumentUrl({
												resourceId: '97',
												queryDesc:
													'角色导出,merchantId:公司Id,roleId:角色Id',
												queryParam: {
													merchantId:
														currentMerchantId,
													roleId,
												},
											})
										}
									}}>
									导出
								</Button>
							</Space>
						</Col>
						<Col sm={{span: 24}}>
							<Table
								className="userTable"
								columns={roleColumns}
								dataSource={roleSource}
								bordered
								loading={roleLoading}
								pagination={false}
								onRow={(record) => ({
									onClick: () => onSelectRow(record),
								})}
								scroll={{y: 550}}
								rowClassName={setRowClassName}
							/>
						</Col>
					</Row>
				</Col>
				<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
					<Row justify="space-between">
						<Col sm={{span: 24}} className="title">
							关联用户
						</Col>
						<Col sm={{span: 24}} className="search">
							<Space size={0}>
								<Search
									placeholder="请输入关联用户"
									allowClear
									value={userNameStr}
									enterButton="搜索"
									onSearch={onUserSearch}
									onChange={(e) => {
										setUserNameStrSource(e.target.value)
									}}
								/>
								<Permissions permissionID="amc_system_permission_roleAddShare_save">
									<Button
										className="marginLeft"
										type="primary"
										onClick={() => onSaveFun()}>
										保存
									</Button>
								</Permissions>
							</Space>
						</Col>
						<Col sm={{span: 24}}>
							<Table
								rowKey="id"
								scroll={{y: 550}}
								rowSelection={rowSelection}
								columns={uesrColumns}
								dataSource={userSource}
								bordered
								loading={userLoading}
								pagination={false}
							/>
						</Col>
					</Row>
				</Col>
				<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
					<Row>
						<Col sm={{span: 24}} className="title">
							已授权限
						</Col>
						<Col sm={{span: 24}} className="no_search">
							<div className="border">
								<Tree
									checkable
									height={580}
									checkedKeys={selectId}
									disabled
									checkStrictly={checkStrictly}
									treeData={menuSource}
									defaultExpandAll
									fieldNames={{
										title: 'name',
										key: 'id',
									}}
								/>
							</div>
						</Col>
					</Row>
				</Col>
			</Row>
		</div>
	)
})

export default connect(({user}: any) => ({
	user,
}))(roleAddShareDom)
